package com.hrsaas.ext.spider.test.handler;

import com.google.common.net.MediaType;
import com.hrsaas.ext.spider.core.CookieStore;
import com.hrsaas.ext.spider.core.HttpClient;
import com.hrsaas.ext.spider.core.ResponseHandler;
import com.hrsaas.ext.spider.util.JsonUtils;

import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpResponseStatus;

/**
 * @author wangxiaoliang
 * 拉钩网返回数据处理
 * @param <T>
 */
public abstract class LGResponseHandler<T> extends ResponseHandler<T> {

	@Override
	protected Object convert(HttpResponseStatus status, HttpHeaders headers, byte[] content) {
		MediaType mediaType = null;
		if (headers.contains(HttpHeaderNames.CONTENT_TYPE)) {
			try {
				mediaType = MediaType.parse(headers.get(HttpHeaderNames.CONTENT_TYPE));
			} catch (Exception ex) {
				// do nothing
			}
			if (MediaType.JSON_UTF_8.subtype().equals(mediaType.subtype())) {
				T result = JsonUtils.fromJson(content, getType());
				return result;
			}
			else if (MediaType.HTML_UTF_8.subtype().equals(mediaType.subtype())) {
				return getConent(content);
			} else if (MediaType.GIF == mediaType) {
				return null;
			}
		}
		throw new IllegalArgumentException("unkonw response content type: " + getConent(content));		
	}

	@Override
	protected boolean receive(HttpResponseStatus status, CookieStore cookieStore, HttpHeaders headers, T object) {
		return true;
	}
	
	@Override
	protected void next(HttpClient client, T object, CookieStore cookieStore, HttpHeaders headers) {
	}
	
	@Override
	protected void onErrorResponse(HttpResponseStatus status, HttpHeaders headers, String content) {
		System.err.println(content);
	}

}
